package com.pw.study.flink.timer;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class TimerEvent {
    public static void main(String[] args) {
       // dealEvent();
        dealEvent2();
    }

    private static void dealEvent2() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> stream = env
                .socketTextStream("hadoop111", 9999)  // 在socket终端只输入毫秒级别的时间戳
                .map(value -> {
                    String[] datas = value.split(",");
                    return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));

                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
                );

        stream
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    private long ts;
                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        if (value.getVc() > 20) {
                           ts = value.getTs() + 5000;
                            System.out.println("定时器: " + ts);
                            ctx.timerService().registerEventTimeTimer(ts);
                        }


                    }

                    // 当定时器触发的时候, 执行这个方法
                    // 参数1: 正在触发的定时器的时间
                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        System.out.println("触发: " + timestamp);
                        out.collect(ctx.getCurrentKey() + " 传感器检测到水位超过20, 红色预警....");
                        ctx.timerService().deleteEventTimeTimer(ts);
                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void dealEvent() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
//数据输入
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop111", 9999).map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] data = value.split(" ");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            }
        });
// 需要增加水位，策略
        WatermarkStrategy<WaterSensor> strategy = WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((SerializableTimestampAssigner<WaterSensor>) (sensor, l) -> sensor.getTs()*1000);

        //
        stream.keyBy(WaterSensor::getId).process(new KeyedProcessFunction<String, WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor sensor, Context ctx, Collector<String> out) throws Exception {
                System.out.println("sensor...."+sensor+" key: "+ctx.getCurrentKey());

                if(sensor.getVc()>50){
                    System.out.println("注册。。。。");
                    long ts = sensor.getTs()+5000;
                    Long tp = ctx.timestamp();
                    System.out.println("timestamp: "+tp+" ts:"+ts);
                    ctx.timerService().registerEventTimeTimer(ts);
                }
                out.collect("执行数据。。。"+sensor);
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                System.out.println("定时服务。。。。"+timestamp);
                out.collect("水位大于50.。。"+ctx.getCurrentKey()+" 传感器检测到水位超过20, 红色预警....");

            }
        }).print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
